﻿package com.controller;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.entity.Uploadfile;
import com.service.OwnerService;
import com.service.UploadService;
import com.service.UserService;
import com.util.DataUtil;
/**
 * 李江杰
 * 2017/3/8
 * 上传图片和相关用户信息
 */
@Controller
@RequestMapping("/uploadfile")
public class UploadController {
	//log4j日志
	public Logger logger=Logger.getLogger(UploadController.class);
	
	@Resource
	UploadService uploadService;
	@Resource
	UserService userService;
	@Resource
	OwnerService ownerService;
	//当前时间
	DataUtil dataUtil=new DataUtil();
	//微信小程序的属性值
	private String fileRoot="/home/apache-tomcat-7.0.47/webapps/image/upload";	//存储图片地址
	public String newfileName;		//图片名称1
	public String newfileName1;		//图片名称2
	public String newfileName2;		//图片名称3
	public String ydetailed;		//单元楼
	public String yname;			//姓名
	public String ysex;				//性别
	public String yowner;			//业主
	public String yphone;			//手机
	public String yaddress;			//地址
	public String ynumber;			//标识用户属于那个业主
	/**
	 * 微信小程序添加注册信息
	 * @param file
	 * @param request
	 * @param upload
	 * @return
	 */
	
	  @Consumes({"multipart/form-data"})
	  @ResponseBody
	  @RequestMapping(value={"/addfile2"}, produces={"application/json;charset=UTF-8"})
	  public String addfile2(@RequestParam(value="filename", required=false) MultipartFile file, HttpServletRequest request, Uploadfile upload){
		System.out.println("进入微信小程序添加信息");
	    this.yname = request.getParameter("yname");
	    this.ysex = request.getParameter("ysex");
	    this.yowner = request.getParameter("yowner");
	    this.yphone = request.getParameter("yphone");
	    this.ydetailed = request.getParameter("ydetailed");
	    this.yaddress = request.getParameter("yaddress");
	    this.ynumber = request.getParameter("ynumber");
	    String file_Name = request.getParameter("name");
	    String yidcar = request.getParameter("yidcar");
	    String roomandnumber = request.getParameter("yfanghao");
	    String unitbuilding = request.getParameter("ydanyuanlou");
	    //下面根据不同照片组取不同的数据
	   if(file_Name.equals("file_pic1")){
	    	 System.out.println("用户第一次上传，进行保存至数据库");
	          String fileName2 = file.getOriginalFilename();
		      String str2 = fileName2.substring(fileName2.indexOf("."));
		      Date data2 = new Date();
		      SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMddHHmmss03");
		      String newData2 = dateFormat2.format(data2);
		      this.newfileName2 = (newData2 + str2);
		      //this.newfileName2 = (newData2 );
		      System.out.println(newfileName2);
		      File targetFile2 = new File(this.fileRoot, this.newfileName2);
		      if (!targetFile2.exists())
		        targetFile2.mkdirs();
		      try
		      {
		        file.transferTo(targetFile2);
		      } catch (Exception e) {
		        e.printStackTrace();
		      }
		      try {
		        SimpleDateFormat createdateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        Date createdata = new Date();
		        String createnewData = createdateFormat.format(createdata);
		        upload.setYfilename("https://wwl.ycws.cc/image/upload/" + this.newfileName2);
		        upload.setYname(URLDecoder.decode(this.yname, "UTF-8"));
		        upload.setYsex(URLDecoder.decode(this.ysex, "UTF-8"));
		        upload.setYowner(URLDecoder.decode(this.yowner, "UTF-8"));
		        upload.setYphone(URLDecoder.decode(this.yphone, "UTF-8"));
		        upload.setYaddress(URLDecoder.decode(this.yaddress, "UTF-8"));
		        upload.setYdetailed(URLDecoder.decode(this.ydetailed, "UTF-8"));
		        upload.setYnumber(URLDecoder.decode(this.ynumber, "UTF-8"));
		        upload.setCreatetime(createnewData);
		        upload.setUpdatetime(createnewData);
		        upload.setYindex("0");
		        upload.setYidcar(URLDecoder.decode(yidcar, "UTF-8"));
		        upload.setRoomandnumber(URLDecoder.decode(roomandnumber, "UTF-8"));
		        upload.setUnitbuilding(URLDecoder.decode(unitbuilding, "UTF-8"));
		      } catch (UnsupportedEncodingException e) {
		        e.printStackTrace();
		      }
		      System.out.println("数据保存提交");
		      uploadService.add(upload);	 
	    }else{
	    	logger.info("未知动作，返回提示");
	    }
	    Map<String,Object> parms=new HashMap<String, Object>();
	    parms.put("code", "00");					//查询成功
		new JSONObject();
		JSONObject jsonObject=JSONObject.fromObject(parms);
	    return jsonObject.toString();
	  }
	  
	  //更新用户头像
	  @Consumes({"multipart/form-data"})
	  @ResponseBody
	  @RequestMapping(value={"/addfile3"}, produces={"application/json;charset=UTF-8"})
	  public String addfile3(@RequestParam(value="filename", required=false) MultipartFile file, HttpServletRequest request, Uploadfile upload){
		System.out.println("更新用户图片");
	
	    String file_Name = request.getParameter("name");
	    String id = request.getParameter("yid");
	    int yid = Integer.parseInt(id);


	    //下面根据不同照片组取不同的数据
	    	System.out.println("用户第一次上传，进行保存至数据库");
	          String fileName2 = file.getOriginalFilename();
		      String str2 = fileName2.substring(fileName2.indexOf("."));
		      Date data2 = new Date();
		      SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMddHHmmss03");
		      String newData2 = dateFormat2.format(data2);
		      this.newfileName2 = (newData2 + str2);
		      System.out.println(newfileName2);
		      //this.newfileName2 = (newData2 );
		      File targetFile2 = new File(this.fileRoot, this.newfileName2);
		      Map<String,Object> parms=new HashMap<String, Object>();
		      try {
				if (!targetFile2.exists())
				    targetFile2.mkdirs();
				    file.transferTo(targetFile2);
				  
				 
				    SimpleDateFormat createdateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				    Date createdata = new Date();
				    String createtime = createdateFormat.format(createdata);
				    String updatetime = createtime;
				    String yfilename="https://wwl.ycws.cc/image/upload/" + this.newfileName2;
				    upload.setYfilename(yfilename);
				    upload.setYid(yid);
				    upload.setCreatetime(createtime);
				    upload.setUpdatetime(updatetime);
				    upload.setExamine("3");
				    upload.setYindex("1");
				    System.out.println(yfilename);
				    System.out.println(id);
				    uploadService.upyfilename(upload);
				    
				    System.out.println("用户修改图片成功"); 
				    
				    parms.put("code", "00");					
					new JSONObject();
					JSONObject jsonObject=JSONObject.fromObject(parms);
					return jsonObject.toString();
			} catch (Exception e) {
				e.printStackTrace();
				parms.put("code", "500");					
				new JSONObject();
				JSONObject jsonObject=JSONObject.fromObject(parms);
				return jsonObject.toString();
			}
			
		        
	  
	  }
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  
	  /*@Consumes({"multipart/form-data"})
	  @ResponseBody
	  @RequestMapping(value={"/addfile2"}, produces={"application/json;charset=UTF-8"})
	  public String addfile2(@RequestParam(value="filename", required=false) MultipartFile file, HttpServletRequest request, Uploadfile upload){
		System.out.println("进入微信小程序添加信息");
	    this.yname = request.getParameter("yname");
	    this.ysex = request.getParameter("ysex");
	    this.yowner = request.getParameter("yowner");
	    this.yphone = request.getParameter("yphone");
	    this.ydetailed = request.getParameter("ydetailed");
	    this.yaddress = request.getParameter("yaddress");
	    this.ynumber = request.getParameter("ynumber");
	    String file_Name = request.getParameter("name");
	    //下面根据不同照片组取不同的数据
	    if(file_Name.equals("file_pic1")){
	    	  System.out.println("用户第一次上传，进行保存至数据库");
	    	  String fileName = file.getOriginalFilename();
		      String str = fileName.substring(fileName.indexOf("."));
		      Date data = new Date();
		      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss01");
		      String newData = dateFormat.format(data);
		      this.newfileName = (newData + str);
		      File targetFile = new File(this.fileRoot, this.newfileName);
		      if (!targetFile.exists())
		        targetFile.mkdirs();
		      try
		      {
		        file.transferTo(targetFile);
		      } catch (Exception e) {
		        e.printStackTrace();
		      }
		      
	    }
	    
	    else if(file_Name.equals("file_pic2")){
	    	 System.out.println("用户第二次上传，进行保存至数据库");
	    	  String fileName1 = file.getOriginalFilename();
		      String str1 = fileName1.substring(fileName1.indexOf("."));
		      Date data1 = new Date();
		      SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyyMMddHHmmss02");
		      String newData1 = dateFormat1.format(data1);
		      this.newfileName1 = (newData1 + str1);
		      File targetFile1 = new File(this.fileRoot, this.newfileName1);
		      if (!targetFile1.exists())
		        targetFile1.mkdirs();
		      try
		      {
		        file.transferTo(targetFile1);
		      } catch (Exception e) {
		        e.printStackTrace();
		      }
	    }else if(file_Name.equals("file_pic3")){
	    	 System.out.println("用户第三次上传，进行保存至数据库");
	          String fileName2 = file.getOriginalFilename();
		      String str2 = fileName2.substring(fileName2.indexOf("."));
		      Date data2 = new Date();
		      SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyyMMddHHmmss03");
		      String newData2 = dateFormat2.format(data2);
		      this.newfileName2 = (newData2 + str2);
		      File targetFile2 = new File(this.fileRoot, this.newfileName2);
		      if (!targetFile2.exists())
		        targetFile2.mkdirs();
		      try
		      {
		        file.transferTo(targetFile2);
		      } catch (Exception e) {
		        e.printStackTrace();
		      }
		      try {
		        SimpleDateFormat createdateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		        Date createdata = new Date();
		        String createnewData = createdateFormat.format(createdata);
		        upload.setYfilename("https://wwl.ycws.cc/image/upload/" + this.newfileName);
		        upload.setYfilename1("https://wwl.ycws.cc/image/upload/" + this.newfileName1);
		        upload.setYfilename2("https://wwl.ycws.cc/image/upload/" + this.newfileName2);
		        upload.setYname(URLDecoder.decode(this.yname, "UTF-8"));
		        upload.setYsex(URLDecoder.decode(this.ysex, "UTF-8"));
		        upload.setYowner(URLDecoder.decode(this.yowner, "UTF-8"));
		        upload.setYphone(URLDecoder.decode(this.yphone, "UTF-8"));
		        upload.setYaddress(URLDecoder.decode(this.yaddress, "UTF-8"));
		        upload.setYdetailed(URLDecoder.decode(this.ydetailed, "UTF-8"));
		        upload.setYnumber(URLDecoder.decode(this.ynumber, "UTF-8"));
		        upload.setCreatetime(createnewData);
		        upload.setUpdatetime(createnewData);
		        upload.setYindex("0");
		      } catch (UnsupportedEncodingException e) {
		        e.printStackTrace();
		      }
		      System.out.println("数据保存提交");
		      uploadService.add(upload);	 
	    }else{
	    	logger.info("未知动作，返回提示");
	    }
	    Map<String,Object> parms=new HashMap<String, Object>();
	    parms.put("code", "00");					//查询成功
		new JSONObject();
		JSONObject jsonObject=JSONObject.fromObject(parms);
	    return jsonObject.toString();
	  }*/
	/**
	 * 根据id查询信息
	 * 返回微信小程序的json数据格式
	 */
	@RequestMapping(value="/wxselectfile",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String wxselectfile(int id,ModelMap map){
		Uploadfile upload=uploadService.select(id);
		map.addAttribute("uploads", upload);
		new JSONObject();
		JSONObject jsonObject=JSONObject.fromObject(map);
		System.out.println(jsonObject);
		return jsonObject.toString();
	} 
	/**
	 * 查询全部信息
	 * 返回微信小程序的json数据格式
	 */
	@RequestMapping(value ="/wxselectAll", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String wxselectAll(ModelMap map){
		List<Uploadfile> uploadfiles=uploadService.selectAll();
		map.addAttribute("uploadfiles", uploadfiles);
		new JSONObject();
		JSONObject jsonObject=JSONObject.fromObject(map);
		System.out.println(jsonObject);
		return jsonObject.toString();
	}
	/**
	 * 根据业主标识查询
	 */
	@RequestMapping(value="/selectYnumber",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String selectYnumber(ModelMap map,int ynumber){
		List<Uploadfile> list=uploadService.selectYnumber(ynumber);
		map.addAttribute("list", list);
		new JSONObject();
		JSONObject jsonObject=JSONObject.fromObject(map);
		System.out.println(jsonObject);
		return jsonObject.toString();
	}
	/**
	 * 修改信息
	 * */
	@ResponseBody
	@RequestMapping("/update")
	public String update(Uploadfile uploadfile){
		System.out.println("进入修改");
		System.out.println(uploadfile.getYname());
		Date updatedata=new Date();
        SimpleDateFormat updatedateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String updatenewData = updatedateFormat.format(updatedata); 
        uploadfile.setUpdatetime(updatenewData);
		uploadService.update(uploadfile);
		Map<String,Object> maps=new HashMap<String,Object>();
		maps.put("code", "00");
		new JSONObject();
		JSONObject josn=JSONObject.fromObject(maps);
		return josn.toString();
	}
	/**
	 * 根据创建时间和小区地址查询用户信息  返回json数据
	 */
	@RequestMapping(value="/selectTimeAddress",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String selectTimeAddress(HttpServletRequest request,ModelMap map){
		Map<String,Object> maps=new HashMap<String, Object>();
		String starttime=request.getParameter("starttime");		//开始时间
		String stoptime=request.getParameter("stoptime");		//结束时间
		String yaddress=request.getParameter("yaddress");		//小区地址
		maps.put("starttime", starttime);
		maps.put("stoptime", stoptime);
		maps.put("yaddress", yaddress);
		List<Uploadfile> list=uploadService.selectTimeAddress(maps);	//查询数据库
		map.addAttribute("list", list);
		new JSONObject();
		JSONObject json=JSONObject.fromObject(map);
		System.out.println(json);
		return json.toString();
	}
	/**
	 * 展示失败的人脸检测
	 * @throws Exception 
	 */
	@RequestMapping("/FailedFaceDetection")
	public String FailedFaceDetection(ModelMap map,String address) throws Exception{
		address = new String(address.getBytes("ISO-8859-1") , "utf-8");
		System.out.println(address);
		List<Uploadfile> list=uploadService.FailedFaceDetection(address);
		map.addAttribute("list", list);
		map.addAttribute("size", list.size());
		return "failedFaceDetection";
	}
	/**
	 * 彩生活注册人数
	 */
	@RequestMapping(value="/cshnumber",method=RequestMethod.GET)
	public String cshnumber(ModelMap modelMap){
		List<Uploadfile> list=uploadService.cshnumber();
		modelMap.addAttribute("list", list);
		modelMap.addAttribute("size", list.size());
		return "cshuserinformation";
	}
}